package api.result;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

public class ResultList implements Result{
    private final List<ResultKV> list = new ArrayList<>();

    public ResultList add(ResultKV item) {
        list.add(item);
        return this;
    }

    public List<ResultKV> getList() {
        return list;
    }

    @Override
    public Result union(Result another) {
        if (another == null) {
            return this;
        } else if (another instanceof ResultList) {
            for (ResultKV item : ((ResultList) another).getList()) {
                this.add(item);
            }
            return this;
        } else if (another instanceof ResultKV) {
            this.add((ResultKV) another);
            return this;
        } else {
            throw new RuntimeException("Unknown result of " + another);
        }
    }

    @Override
    public void show() {
        System.out.print(this.toString());
    }

    @Override
    public void show(PrintStream printStream) {
        printStream.print(this.toString());
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (ResultKV item : list) {
            sb.append(item.toString()).append('\n');
        }
        return sb.toString();
    }
}
